/**
 * Copyright 2013 ABSir's Studio
 * 
 * All right reserved
 *
 * Create on 2013-6-21 下午4:24:56
 */
package com.absir.android.view;

import java.lang.reflect.Field;

import android.view.View;
import android.view.ViewManager;

import com.absir.android.view.annotation.InjectFlater;
import com.absir.core.kernel.KernelLang.CauseRuntimeException;
import com.absir.core.kernel.KernelObject;

/**
 * @author absir
 * 
 */
public class InjectViewFlater extends InjectViewAbstract {

	/**
	 * @param injectExcutorObject
	 * @param injectFlater
	 * @param field
	 */
	public static void injectFlaterView(InjectExcutorObject<Object> injectExcutorObject, InjectFlater injectFlater, Field field) {
		View value = injectExcutorObject.loadView(injectFlater.value(), "layout", field == null ? null : field.getName());
		if (value != null) {
			injectExcutorObject.addFlaterView(value);
			Object target = injectFlater.superViewId() > 0 ? injectExcutorObject.findViewById(injectFlater.superViewId(), null, null) : KernelObject.expressGetter(injectExcutorObject.getObject(),
					injectFlater.superViewTarget());
			if (target != null && target instanceof ViewManager) {
				((ViewManager) target).addView(value, null);
			}

			if (field != null) {
				if (field.getType().isAssignableFrom(value.getClass())) {
					try {
						field.set(injectExcutorObject.getObject(), value);

					} catch (Exception e) {
						// TODO Auto-generated catch block
						new CauseRuntimeException(e);
					}
				}
			}
		}
	}

	/** field */
	private Field field;

	/** injectFlater */
	private InjectFlater injectFlater;

	/**
	 * @param field
	 * @param injectFlater
	 */
	public InjectViewFlater(Field field, InjectFlater injectFlater) {
		field.setAccessible(true);
		this.field = field;
		this.injectFlater = injectFlater;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.absir.android.view.InjectViewAbstract#injectExcutor(com.absir.android
	 * .view.InjectExcutorObject)
	 */
	@Override
	public void injectExcutor(InjectExcutorObject<Object> injectExcutorObject) {
		// TODO Auto-generated method stub
		injectFlaterView(injectExcutorObject, injectFlater, field);
	}
}
